import React, { useState, useRef } from 'react';
import { connect } from 'react-redux';
import { View, Button } from '@tarojs/components';
import Taro, { useDidShow, getCurrentInstance } from '@tarojs/taro';
import { appid } from '@/src/config';

import './index.scss';

const Door = ({ getUserPhone, appName }) => {
  const goInfo = () => {
    Taro.navigateTo({ url: '/pages/mainPages/bindWalletUseInfo/index' });
  };
  return (
    <View className={'door' + (appName == 'suXiaoFu' ? ' bg_suXiaoFu' : '')}>
      <View className="tip" onClick={goInfo}>
        使用攻略
      </View>
      <Button className="btn" openType="getPhoneNumber" onGetPhoneNumber={getUserPhone}>
        绑定中行数字钱包
      </Button>
    </View>
  );
};

const BindWalletPage = ({ dispatch }) => {
  const code = useRef();
  const [appName, setAppName] = useState('taiHuJiShi');

  useDidShow(() => {
    let urlParms = getCurrentInstance().router.params || {};
    if (urlParms.appName && urlParms.appName != appName) {
      Taro.setNavigationBarTitle({
        title: urlParms.appName == 'suXiaoFu' ? '苏小福' : '',
      });
      setAppName(urlParms.appName);
      dispatch({
        type: 'otherApi/setAppNameForBankBind',
        payload: urlParms.appName,
      });
    }
    process.env.TARO_ENV !== 'h5' &&
      Taro.login({
        success: (res) => {
          code.current = res.code;
        },
      });
  }, []);

  const getUserPhone = (e) => {
    const { encryptedData, iv, errMsg } = e.detail;
    if (-1 != errMsg.indexOf('ok')) {
      dispatch({
        type: 'login/loginByWallet',
        payload: {
          username: appid,
          loginType: 'WECHAT_MINIPROGRAM',
          password: code.current,
          wechatInfoReq: {
            encryptedData,
            iv,
          },
        },
      }).then(() => {
        dispatch({
          type: 'otherApi/checkWalletBindStatus',
          payload: {},
        });
      });
    } else if (-1 != errMsg.indexOf('deny')) {
      Taro.showModal({
        title: '提示',
        content:
          '您已拒绝，将无法绑定中行数字钱包；如要继续绑定，请再次点击绑定按钮，并在微信授权窗口点击允许',
      });
    }
  };

  return (
    <View className="totalPage_bindWallet">
      <Door getUserPhone={getUserPhone} appName={appName} />
    </View>
  );
};

export default connect(({}) => ({}))(BindWalletPage);
